<!--
 * @Author: zi.yang
 * @Date: 2021-03-13 22:22:12
 * @LastEditors: zi.yang
 * @Description: 键盘输入提示页
 * @FilePath: \vue-music\src\components\view\search-suggest.vue
-->
<template>
  <div class="search-suggest">
    <div class="search-suggest-head">搜索“ {{ suggestWord }} ”</div>
    <div
      class="search-suggest-item"
      v-for="(item, index) in suggestResult"
      :key="index"
      @click="handleToList(item.name)"
    >
      <i class="iconfont iconsearch "></i>{{ item.name }}
    </div>
  </div>
</template>

<script lang="ts">
/* global Readonly:false */
import {
  reactive, toRefs, watch, defineComponent, ref,
} from '@vue/composition-api';

type tResult = {
  searchWord:string,
  result:Object,
}
type tState = {
  suggestWord:string,
  suggestResult:Object,
  handleToList:(keyword:string)=>void
}

export default defineComponent({
  name: 'search-suggest',
  props: ['result'],
  // TS：属性或参数中使用 ?: 表示该属性或参数为可选项
  setup(
    props: Readonly<{result?: tResult}>,
    context:Readonly<{emit : (event: string, ...args: any[]) => void}>,
  ) {
    // 拦截器,需要返回一个空的 ref 保证下面的 return 不会误读
    if (props.result === null || props.result === undefined) return ref();
    const { emit } = context;
    const state:tState = reactive({
      suggestWord: props.result.searchWord,
      suggestResult: props.result.result,
      handleToList(keyword:string) {
        emit('setKeyword', keyword);
      },
    });

    // FIXME: watch 第一个参数，强制跳过了类型检查
    watch(
      // @ts-ignore
      () => props.result,
      (result:tResult) => {
        state.suggestWord = result.searchWord;
        state.suggestResult = result.result;
      },
    );
    return toRefs(state);
  },
});
</script>

<style scoped>
.search-suggest {
  padding: 15px;

  border-top: 1px #e4e4e4 solid;

  font-size: 14px;
}
.search-suggest-head {
  margin-bottom: 37px;

  color: #4574a5;
}
.search-suggest-item {
  margin-bottom: 37px;

  color: #5d5d5d;
}
.search-suggest-item i {
  position: relative;
  top: 1px;

  margin-right: 14px;

  color: #bdbdbd;
}
</style>
